package com.hopu.proxy.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * CGLib动态代理
 */
public class CGLibProxy implements MethodInterceptor {

    //被代理对象
    private Object target;

    /**
     * 创建代理对象
     * @param target
     * @return
     */
    public Object createProxy(Object target){
        this.target = target;
        //创建Enhancer对象
        Enhancer enhancer = new Enhancer();
        //设置被代理对象的类为父类
        enhancer.setSuperclass(this.target.getClass());
        //设置方法拦截的回调
        enhancer.setCallback(this);
        //返回代理类的对象
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("CGLib给产品打广告！");
        //调用被代理对象的方法
        Object obj  = method.invoke(target,objects);
        System.out.println("CGLib给产品做售后！");
        return obj;
    }
}
